/*
 * Copyright (c) 2004-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Kevin Lim
 */

#include "base/intmath.hh"
#include "base/trace.hh"
#include "cpu/edge/pred/btb.hh"

DefaultBTB::DefaultBTB(unsigned _numEntries,
                       unsigned _offsetLength,
                       unsigned _blockShiftAmt)
    : numEntries(_numEntries),
      offsetLength(_offsetLength),
      blockShiftAmt(_blockShiftAmt)
{
    DPRINTF(EdgePredUnit, "BTB: Creating BTB object.\n");

    if (!isPowerOf2(numEntries)) {
        fatal("BTB entries is not a power of 2!");
    }

    btb.resize(numEntries);

    for (unsigned i = 0; i < numEntries; ++i) {
        btb[i].offset = 0;
        btb[i].hysteresis = 0;
        btb[i].isupdated = false;
    }

    idxMask = numEntries - 1;
    idxLength = floorLog2(numEntries);

    offsetMask = (1 << offsetLength) - 1;
    DPRINTF(EdgePredUnit,"The number of bits to shift block address is %i.\n",blockShiftAmt);
    DPRINTF(EdgePredUnit,"Offset length is %i, offset Mask is %#x.\n",offsetLength,offsetMask);
}

void
DefaultBTB::reset()
{
    for (unsigned i = 0; i < numEntries; ++i) {
        btb[i].hysteresis = 0;
        btb[i].offset = 0;
    }
}

inline
unsigned
DefaultBTB::getIndex(const Addr &block_pc, int addr_space_id, ExitID exitID)
{
    // Need to shift PC over by the word offset.
  assert (addr_space_id >= 0 && addr_space_id <= 15);
  int reversed_as_id = ((addr_space_id & 0x1) << 3)
                        | ((addr_space_id & 0x2) << 1)
                        | ((addr_space_id & 0x4) >> 1)
                        | ((addr_space_id & 0x8) >> 3);

  assert (exitID >= 0 && exitID <= 7);
  int reversed_exit = ((exitID & 0x1) << 2)
                       | (exitID & 0x2)
                       | ((exitID & 0x4) >> 2);

  int index = ((block_pc >> blockShiftAmt)
               ^ ( (reversed_exit << (idxLength - 3)) |
                   (reversed_as_id << (idxLength - 7)) ) )
              & idxMask;

  return index;
}

Addr
DefaultBTB::targetGen(Addr block_pc, Addr offset)
{
    Addr newOffset;
    newOffset = offset & offsetMask;
    DPRINTF(EdgePredUnit,"newoffset = %#x.\n",newOffset);

    if ((newOffset >> (offsetLength- 1)) & 0x1) // negative within those 9 bits
       newOffset = newOffset | (~offsetMask);

    DPRINTF(EdgePredUnit,"newoffset = %#x.\n",newOffset);
    DPRINTF(EdgePredUnit,"target = %#x.\n",block_pc + (newOffset << blockShiftAmt));

    return block_pc + (int64_t)(newOffset << blockShiftAmt);
}

// @todo Create some sort of return struct that has both whether or not the
// address is valid, and also the address.  For now will just use addr = 0 to
// represent invalid entry.
Addr
DefaultBTB::lookup(const Addr &block_pc, int addr_space_id, ExitID exitID)
{
    unsigned btb_idx = getIndex(block_pc, addr_space_id, exitID);
    Addr offset = btb[btb_idx].offset;
    Addr target = targetGen(block_pc,offset);
    if (btb[btb_idx].isupdated) {
        DPRINTF(EdgePredUnit,"Block [PC=%#x,Exit=%i,idx=%#x] BTB updated before.\n",
                block_pc,exitID,btb_idx);
    } else {
        DPRINTF(EdgePredUnit,"Block [PC=%#x,Exit=%i,idx=%#x] BTB first access.\n",
                block_pc,exitID,btb_idx);
    }
    return target;
}

void
DefaultBTB::update(const Addr &block_pc, int addr_space_id, ExitID exitID,
        const Addr &target)
{
    BTBEntry oldBTBEntry,newBTBEntry;

    unsigned btb_idx = getIndex(block_pc, addr_space_id, exitID);

    Addr offset = ((target - block_pc)) >> blockShiftAmt;
    
    assert(btb_idx < numEntries);

    oldBTBEntry = btb[btb_idx];

    newBTBEntry.offset = oldBTBEntry.hysteresis ? oldBTBEntry.offset : offset;

    newBTBEntry.hysteresis = (oldBTBEntry.offset == offset);

    newBTBEntry.isupdated = true;

    btb[btb_idx] = newBTBEntry;

    DPRINTF(EdgePredUnit,"Block [PC=%#x,Exit=%i,idx=%#x]"
            " BTB updated(target = %#x,%#x).\n"
            "Offset change from %#x to %#x.\n",
            block_pc,
            exitID,
            btb_idx,
            target,
            target-block_pc,
            oldBTBEntry.offset,
            offset);

    if (newBTBEntry.hysteresis) {
        DPRINTF(EdgePredUnit,"hyst = 1.\n");
    } else {
        DPRINTF(EdgePredUnit,"hyst = 0.\n");
    }
}

